﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RH.Common.Extensions;
using RH.Domain;
using RH.Web.ViewModels;
using RH.Web.Utility;
using AutoMapper;
using RH.Common.Xml;
using System.Data;
using RH.Web.ViewModels.UtilityModels;

namespace RH.Web.Areas.Admin.Controllers
{
    [Authorize(Roles = "Admin")]
    public class CategoryController : BaseController
    {
		private AppEntities _Context = new AppEntities();
        
		public CategoryController()
		{
		}

		public CategoryController(UserViewModel currentUser)
			: base(currentUser)
        {
        }

        public ActionResult Index()
        {
            return View();
        }
		/// <summary>
        /// Gets a Category from Database to edit
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
		public ActionResult Edit(int id = 0)
        {
            Category entity = id == 0 ? new Category() : _Context.Categories.FirstOrDefault(P => P.ID == id);            
            CategoryViewModel viewModel = Mapper.Map<Category, CategoryViewModel>(entity);
            //viewModel.PropertyDefinition = viewModel.PropertyDefinition.Replace("\n", Environment.NewLine);
            return View(viewModel);
        }

		/// <summary>
        /// Saves Category Information into the Database
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
		[HttpPost]
		public ActionResult Edit(CategoryViewModel viewModel)
        {
			if (!ModelState.IsValid)
                return View(viewModel);

            #region ZGL Validation
            //FIXME: This needs to be moved to ZGL creation Admin Pages
            //As ZGL has now moved to ZGL table so this validation is required here
            ///Check the Invalid Property Definition XML             
            //if (viewModel.PropertyDefinition.IsEmpty())
            //{
            //    if (viewModel.ParentID != null && viewModel.ParentID.GetValueOrDefault() > 0) //First Level
            //    {
            //        CategoryViewModel parentCategory = ApplicationCache.Categories.FirstOrDefault(P => P.ID == viewModel.ParentID); //Second Level
            //        if (parentCategory.ParentCategory != null) //Third Level
            //        {
            //            ModelState.AddModelError("PropertyDefinition", "Please Enter Property Definition XML.");
            //            return View(viewModel);
            //        }
            //    }
            //}
            //else
            //{
            //    try
            //    {
            //        var childs = ApplicationCache.Categories.FirstOrDefault(P => P.ParentID == viewModel.ID);
            //        var parentCategory = ApplicationCache.Categories.FirstOrDefault(P => P.ID == viewModel.ParentID.GetValueOrDefault());
            //        if (childs != null || viewModel.ParentID.GetValueOrDefault() == 0 || (parentCategory != null && parentCategory.ParentCategory == null))
            //        {
            //            ModelState.AddModelError("PropertyDefinition", "Property Definitions are not allowed in parent categories.");
            //            return View(viewModel);
            //        }
            //        ViewModels.ZGL.Category.Category categoryLGL = XmlHelper.ToObject<ViewModels.ZGL.Category.Category>(viewModel.PropertyDefinition);
            //    }
            //    catch (Exception ex)
            //    {
            //        ModelState.AddModelError("PropertyDefinition", String.Format("Property Definition XML does not satisfy Zealous Graphical Language (LGL) Specification. Correct following Error and try again:<br/>{0}", ex.InnerException.Message));
            //        return View(viewModel);
            //    }
            //}
            #endregion ZGL Validation

            if (_Context.IsDuplicateCategory(viewModel.Name.ToSeoUrl(), viewModel.ID))
            {
                ModelState.AddModelError("DuplicateCategory", "This category already exists. Please choose another.");
                return View(viewModel);
            }

            Category entity = null; 
			if (viewModel.ID == 0)
            {
                entity = new Category();                
                _Context.AddToCategories(entity);
            }
            else
                entity = _Context.Categories.FirstOrDefault(P => P.ID == viewModel.ID);

            entity = Mapper.Map<CategoryViewModel, Category>(viewModel, entity);
            entity.UrlName = entity.Name.ToSeoUrl();

            if (entity.ParentID == 0)
                entity.ParentID = null;

            _Context.SaveChanges();
            ApplicationCache.RefreshCategoryCache();
            return RedirectToAction("List");        
        }

        public ActionResult List()
        {
            UtilityDAO dao = new UtilityDAO();
            RH.Domain.DbParameter[] parameters = new[]{
                new RH.Domain.DbParameter("@CategoryID", 0)
            };
            DataSet ds = dao.GetDataSet(DbObject.SP.GET_CATEGORY, parameters, true);
            //DataTable dt = BuildDataTable();
            //DateTime start = DateTime.Now;
            ListConfig config = RH.Web.ViewModels.UtilityModels.ListConfigBuilder.Build(
                @"Info{ ID | Name | Urlname | ParentID }, 
                Details{Description | PropertyDefinition}",
                ds.Tables[0], "/Admin/Category/Edit/{0}");

            //Picture{Image:<img src='/ProductImages/{0}' alt='{1}' title='{2}' />(ThumbImage ~ ID ~ Name)},
            //Description{Description}

            //ViewBag.ListConfig = config;
            ViewData[AppConstants.ViewDataKeys.LIST_CONFIG] = config;
            return View();
        }
    }
}
